<template>
    <div class="app-container">
        <el-form :inline="true" :model="queryParams" ref="queryForm">
            <el-form-item label="公司名称" prop="name">
                <el-input
                        v-model="queryParams.name"
                        placeholder="请输入公司名称"
                        clearable
                        size="small"
                />
            </el-form-item>
            <el-form-item label="公司注册码" prop="idCode">
                <el-input
                        v-model="queryParams.idCode"
                        placeholder="请输入公司注册码"
                        clearable
                        size="small"
                />
            </el-form-item>
            <el-form-item label="公司类型" prop="type">
                <el-select v-model="queryParams.type" placeholder="公司类型" clearable size="small">
                    <el-option
                            v-for="dict in typeOptions"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="公司法人" prop="legalPerson">
                <el-input
                        v-model="queryParams.legalPerson"
                        placeholder="请输入公司法人"
                        clearable
                        size="small"
                />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
                <el-button type="success" icon="el-icon-plus" size="mini" @click="handleAdd"
                           v-hasPermi="['organization:company:addCompany']">新增
                </el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetForm('queryForm')">重置</el-button>
            </el-form-item>
        </el-form>

        <el-table v-loading="loading" border :data="companyList">
            <el-table-column label="序号" type="index" width="80"/>
            <el-table-column label="公司名称" prop="name" :show-overflow-tooltip="true"/>
            <el-table-column label="公司注册码" prop="idCode" :show-overflow-tooltip="true"/>
            <el-table-column label="公司类型" prop="type" width="100"/>
            <el-table-column label="公司法人" prop="legalPerson" width="100"/>
            <el-table-column label="操作时间" align="center" prop="updateTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.updateTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleUpdate(scope.row)"
                            v-hasPermi="['organization:company:modifyCompany']"
                    >修改
                    </el-button>
                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-circle-check"
                            @click="handleCompanyDoc(scope.row)"
                            v-hasPermi="['document:queryDocByCompanyId']"
                    >附件管理
                    </el-button>
                    <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-delete"
                            @click="handleDelete(scope.row)"
                            v-hasPermi="['organization:company:delCompany']"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination
                v-show="total>0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
        />
        <!-- 修改公司信息对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
            <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="130px">
                <el-form-item label="公司名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入公司名称" show-word-limit readonly
                              :style="{width: '100%'}"></el-input>
                </el-form-item>
                <el-form-item label="公司注册码" prop="idCode">
                    <el-input v-model="formData.idCode" placeholder="请输入公司注册码" show-word-limit readonly
                              :style="{width: '100%'}"></el-input>
                </el-form-item>
                <el-form-item label="公司法人" prop="legalPerson">
                    <el-input v-model="formData.legalPerson" placeholder="请输入公司法人" show-word-limit clearable
                              :style="{width: '100%'}"></el-input>
                </el-form-item>
                <el-form-item label="公司类型" prop="type">
                    <el-radio-group v-model="formData.type" size="medium">
                        <el-radio v-for="(item, index) in typeOptions" :key="index" :label="item.dictValue" disabled>
                            {{item.dictLabel}}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="formData.phone" placeholder="请输入联系电话" show-word-limit clearable
                              :style="{width: '100%'}"></el-input>
                </el-form-item>
                <el-form-item label="公司邮箱" prop="email">
                    <el-input v-model="formData.email" placeholder="请输入公司邮箱" show-word-limit clearable
                              :style="{width: '100%'}"></el-input>
                </el-form-item>
                <el-form-item label="公司地址" prop="address">
                    <el-input v-model="formData.address" placeholder="请输入公司地址" show-word-limit clearable
                              :style="{width: '100%'}"></el-input>
                </el-form-item>
                <el-form-item label="公司网址" prop="website">
                    <el-input v-model="formData.website" placeholder="请输入公司网址" show-word-limit clearable
                              :style="{width: '100%'}"></el-input>
                </el-form-item>
                <el-form-item label="经营范围" prop="companyRegistry">
                    <el-input v-model="formData.companyRegistry" type="textarea" placeholder="请输入经营范围"
                              show-word-limit
                              :autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
                </el-form-item>
                <el-form-item label="公司Logo" prop="logoWeb">
                    <el-upload ref="logoWeb"
                               :file-list="logoWebfileList"
                               :auto-upload="false"
                               :before-upload="logoWebBeforeUpload"
                               :limit="2"
                               action=""
                               :on-change="onChange"
                               list-type="picture-card"
                               accept="image/*">
                        <i class="el-icon-plus"></i>
                        <div slot="tip" class="el-upload__tip">只能上传不超过 5MB 的image/*文件</div>
                    </el-upload>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 公司附件信息列表 -->
        <el-dialog title="公司附件管理" :visible.sync="docOpen" width="900px" append-to-body>
            <el-table border :data="documentList">
                <el-table-column label="序号" type="index" width="60"/>
                <el-table-column label="附件名称" prop="docName" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-download"
                                @click="downloadDoc(scope.row)"
                                v-hasPermi="['document:downloadDoc']"
                        >{{scope.row.docName}}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="存储路径" prop="docUrl" :show-overflow-tooltip="true"/>
                <el-table-column label="操作时间" align="center" prop="updateTime" width="180">
                    <template slot-scope="scope">
                        <span>{{ parseTime(scope.row.updateTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="80" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-delete"
                                @click="handleDelDoc(scope.row)"
                                v-hasPermi="['document:delDocById']"
                        >删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-form ref="elForm" size="medium" label-width="80px" style="padding: 30px 0px;">
                <el-form-item label="新增附件" prop="appendixFile">
                    <el-upload ref="appendixFile"
                               :file-list="appendixFilefileList"
                               action=""
                               :auto-upload="false"
                               :limit="10"
                               :on-exceed="OnExceed"
                               multiple
                               :before-upload="appendixFileBeforeUpload">
                        <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">最多只能上传10个文件，单个文件大小不超过 10MB</div>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-hasPermi="['document:addDocument']" @click="submitAppendixFile">确 定 新 增</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
    import {listCompany,modifyCompany,delCompany} from "@/api/organization/company.js";
    import {queryDocByCompanyId,downloadDoc,delDocById,addDocument} from "@/api/document/document.js";

    export default {
        name: "company",
        components: {},
        data() {
            return {
                // 公司数据
                companyList: [],
                // 总条数
                total: 0,
                // 遮罩层
                loading: true,
                // 弹出层标题
                title: "",
                // 是否显示弹出层
                open: false,
                // 公司类型数据字典
                typeOptions: [],
                // 查询参数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    name: undefined,
                    idCode: undefined,
                    type: undefined,
                    legalPerson: undefined
                },
                // 表单参数
                formData: {},
                realFormData: new FormData(),
                // 表单校验
                rules: {
                    name: [{
                        required: true,
                        message: '请输入公司名称',
                        trigger: 'blur'
                    }],
                    idCode: [{
                        required: true,
                        message: '请输入公司注册码',
                        trigger: 'blur'
                    }],
                    legalPerson: [{
                        required: true,
                        message: '请输入公司法人',
                        trigger: 'blur'
                    }],
                    type: [{
                        required: true,
                        message: '公司类型不能为空',
                        trigger: 'change'
                    }],
                    phone: [{
                        required: true,
                        message: '请输入联系电话',
                        trigger: 'blur'
                    }],
                    email: [],
                    address: [],
                    website: [],
                    companyRegistry: [{
                        required: true,
                        message: '请输入经营范围',
                        trigger: 'blur'
                    }],
                },
                logoWebfileList: [],
                docOpen: false,
                documentList: [],
                /*附件添加列表*/
                appendixFilefileList: [],
                openCompanyDocInfo: null,
                appendixFileForm: new FormData()
            };
        },
        created() {
            this.getList();
            this.getDicts("sys_company_type").then(response => {
                this.typeOptions = response.data;
            });
        },
        methods: {
            /** 查询按钮操作 */
            handleQuery() {
                this.getList();
            },
            /** 查询公司列表 */
            getList() {
                this.loading = true;
                listCompany(this.queryParams).then(
                    response => {
                        this.companyList = response.rows;
                        this.total = response.total;
                        this.loading = false;
                    }
                );
            },
            /** 新增按钮操作 */
            handleAdd() {
                //跳转到新增页面
                this.$router.push({path: "/company/addCompany"});
            },
            /** 修改按钮操作 */
            handleUpdate(row) {
                //将现有的公司logo图片展示
                let data = {
                    busiId: row.companyId,
                    docType: "公司Logo"
                };
                queryDocByCompanyId(data).then(response => {
                    if (response.data != null && response.data.length > 0) {
                        let docementObj = response.data;
                        let logoWebObj = [{
                            name: docementObj[0].docName,
                            url: process.env.VUE_APP_BASE_API + docementObj[0].docUrl
                        }]
                        this.logoWebfileList = logoWebObj;
                    }
                });

                //添加其他数据
                //将列表中的选中对象信息拷贝到修改界面的对象中去,assign方法很重要，防止取消之后影响分页表格数据
                this.formData = Object.assign({}, row);
                this.open = true;
                this.title = "修改公司信息";
            },
            // 取消按钮
            cancel() {
                this.open = false;
            },
            /** 提交按钮 */
            submitForm: function () {
                this.$refs["elForm"].validate(valid => {
                    if (valid) {
                        let app = this;
                        setTimeout(function () {
                            //上传函数，如果把提交函数用在http-request钩子中，
                            // fileList多长就执行请求多少次接口，依旧是无法做到只请求一次上传多文件
                            //  用FormData存放上传文件
                            app.realFormData.append("companyId",app.formData.companyId);
                            app.realFormData.append("name",app.formData.name);
                            app.realFormData.append("idCode",app.formData.idCode);
                            app.realFormData.append("legalPerson",app.formData.legalPerson);
                            app.realFormData.append("type",app.formData.type);
                            app.realFormData.append("phone",app.formData.phone);
                            app.realFormData.append("email",app.formData.email);
                            app.realFormData.append("address",app.formData.address);
                            app.realFormData.append("website",app.formData.website);
                            app.realFormData.append("companyRegistry",app.formData.companyRegistry);
                            //进行elementUi上传组件的提交触发
                            app.$refs['logoWeb'].submit();

                            modifyCompany(app.realFormData).then(response => {
                                if (response.code === 200) {
                                    app.msgSuccess("修改公司信息成功！");
                                    app.getList();
                                    app.open = false;
                                } else {
                                    app.msgError(response.msg);
                                }
                            });
                            app.realFormData = new FormData();
                        },1000);
                    }
                });
            },
            logoWebBeforeUpload(file) {
                let isRightSize = file.size / 1024 / 1024 < 5
                if (!isRightSize) {
                    this.$message.error('文件大小超过 5MB')
                }
                let isAccept = new RegExp('image/*').test(file.type)
                if (!isAccept) {
                    this.$message.error('应该选择image/*类型的文件')
                }

                if (isRightSize && isAccept) {
                    this.realFormData.append('logoWebFile', file);
                    return false;
                } else {
                    return false;
                }
            },
            onChange(file, fileList){
                if (fileList.length > 1) {
                    fileList.splice(0, 1);
                }
            },
            /** 删除按钮操作 */
            handleDelete(row) {
                let app = this;
                if(row.type == "系统公司"){
                    this.msgError("系统公司不允许删除！");
                    return;
                }
                this.$confirm('是否确定删除名称为"' + row.name + '"的公司?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function () {
                    delCompany(row).then(response => {
                        if (response.code === 200) {
                            app.msgSuccess("删除成功");
                            app.getList();
                        } else {
                            app.msgError(response.msg);
                        }
                    });
                });
            },
            /** 附件管理按钮 */
            handleCompanyDoc(row){
                this.openCompanyDocInfo = row;
                //将现有公司附件信息查询
                let data = {
                    busiId: row.companyId,
                    docType: "公司创建附件"
                };
                queryDocByCompanyId(data).then(response => {
                    this.documentList = response.data;
                });

                this.docOpen = true;
            },
            /** 附件删除处理 */
            handleDelDoc(row){
                this.$confirm('确定要删除该文件？删除后将无法恢复！', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(response => {
                    delDocById(row).then(response => {
                        if (response.code === 200) {
                            this.msgSuccess("删除成功");
                            //将现有公司附件信息查询
                            let data = {
                                busiId: row.busiId,
                                docType: "公司创建附件"
                            };
                            queryDocByCompanyId(data).then(response => {
                                this.documentList = response.data;
                            });
                        } else {
                            this.msgError(response.msg);
                        }
                    })
                })
            },
            downloadDoc(row){
                this.$confirm('确定下载该文件？', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(response => {
                    downloadDoc(row);
                })
            },
            OnExceed(file, fileList) {
                this.$message.error(`最多只能上传10个文件!`);
            },
            appendixFileBeforeUpload(file) {
                let isRightSize = file.size / 1024 / 1024 < 10
                if (!isRightSize) {
                    this.$message.error('文件大小超过 10MB')
                }

                if (isRightSize) {
                    this.appendixFileForm.append('appendixFile', file);
                    return false;
                } else {
                    return false;
                }
            },
            submitAppendixFile(){
                let app = this;
                setTimeout(function () {
                    //上传函数，如果把提交函数用在http-request钩子中，
                    // fileList多长就执行请求多少次接口，依旧是无法做到只请求一次上传多文件
                    //  用FormData存放上传文件
                    app.appendixFileForm.append("busiId",app.openCompanyDocInfo.companyId);
                    app.appendixFileForm.append("docType","公司创建附件");
                    app.appendixFileForm.append("remark","创建" + app.openCompanyDocInfo.name + "的附件");
                    //进行elementUi上传组件的提交触发
                    app.$refs['appendixFile'].submit();

                    addDocument(app.appendixFileForm).then(response => {
                        if (response.code === 200) {
                            app.msgSuccess("添加公司附件成功！");
                            //将现有公司附件信息查询
                            let data = {
                                busiId: app.openCompanyDocInfo.companyId,
                                docType: "公司创建附件"
                            };
                            queryDocByCompanyId(data).then(response => {
                                app.documentList = response.data;
                            });
                            app.open = false;
                        } else {
                            app.msgError(response.msg);
                        }
                    });
                    app.appendixFileForm = new FormData();
                },1000);
            }
        }
    };
</script>
